/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "settingssql.h"

#include <QDir>
#include <QMap>
#include <QString>
#include <QStringList>
#include <QVariant>
#include <QFileInfo>

#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>

#include <QDebug>

//use for debug
#define DEBUG_SETTINGS


/*!
	\class SettingsSQL
	\brief An alternative to the application-wide QSettings that is more
	suitable for storing large amounts of data.

	The settings database is SQLite based, and lazily retrieves data when it
	is asked for. It also does incremental updates of the database rather than
	rewriting the whole file each time one of the settings change.

	The SettingsSQL API mimics that of QSettings.
*/


typedef QMap<QString, QVariant> SettingsMap;

class SettingsSQL::SettingsSQLPrivate{
public:
	SettingsSQLPrivate(){}
	QString effectiveGroup() const{
		return m_groups.join(QString(QLatin1Char('/')));
	}

	QString effectiveKey(const QString &key) const{
		QString g = effectiveGroup();
		if (!g.isEmpty() && !key.isEmpty())
			g += QLatin1Char('/');
		g += key;
		return g;
	}

	SettingsMap m_settings;

	QStringList m_groups;
	QStringList m_dirtyKeys;

	SettingsSQL::Scope m_scope;

	QSqlDatabase m_db;
};

bool SettingsSQL::canUse() const {
	return QSqlDatabase::drivers().contains("QSQLITE");
}


SettingsSQL::SettingsSQL(const SettingsSQL::Scope &scope,
						 const QString &application, const QString &path,
						 const QString &_fileName, QObject *parent) :
	QObject(parent),
	d(new SettingsSQLPrivate())
{
	d->m_scope = scope;
	const QLatin1Char slash( '/' );


	// TODO: Don't rely on a path, but determine automatically
	QDir pathDir( path );
	if( path.isEmpty() ){
		QString variable;
#if defined(Q_WS_WIN)
		if( SettingsSQL::GlobalScope == d->m_scope ){
			variable = "ALLUSERSPROFILE";
		}else{
			variable = "APPDATA";
		}
		pathDir.setPath(QString("%1/%2").
						arg( QString(qgetenv(variable.toLatin1().data())),
							 application) );
#elif defined(Q_WS_MAC)
		variable = QString("/Library/Application Support/%1").
				   arg(application);
		if( SettingsSQL::GlobalScope == d->m_scope )
			pathDir.setPath(variable);
		else
			pathDir.setPath( variable.prepend("~") );

#else
		//TODO
		//find path where linux store shared data
		pathDir.setPath(  QString("$1/.%2").arg( QString(qgetenv("HOME")),
												 application.toLower()) );
#endif
	}


	if( !pathDir.exists() ){
		if( !pathDir.mkpath( pathDir.absolutePath() ) ){
			qWarning() << "SettingsSQL -> Constructor -> cannot create 'path'";
		}

	}

	QString fileName = pathDir.absolutePath();
	if( !fileName.endsWith( slash ) )
		fileName += slash;

	if( _fileName.isEmpty() )
		fileName += application.toLower();
	else{
		QFileInfo fi(_fileName);
		fileName += fi.baseName();
	}

	fileName += QLatin1String( ".sqlite" );

	d->m_db = QSqlDatabase::addDatabase( "QSQLITE", "settings" );
	d->m_db.setDatabaseName( fileName );

	if( !d->m_db.open() ){
		qWarning().nospace() << "Warning: Failed to open settings database at "
				<< fileName << " ("
				<< d->m_db.lastError().driverText() << ")";
	} else {

		QSqlQuery query( d->m_db );

		//optimizations

		query.exec("PRAGMA temp_store = 2;"); //temporary storage in memory

		query.exec("PRAGMA encoding = \"UTF-8\";");//set encoding to UTF-8

		query.exec("PRAGMA synchronous=OFF;"); //not wait to disk
											   //(only for settings)

		query.exec("PRAGMA locking_mode=EXCLUSIVE;"); //exclusive lock file


		// Create the settings table if it doesn't exist yet
		query.prepare( QLatin1String("CREATE TABLE IF NOT EXISTS settings ("
									 "key PRIMARY KEY ON CONFLICT REPLACE, "
									 "value)"));
		if( !query.exec() )
			qWarning().nospace() <<
					"Warning: Failed to prepare settings database! ("
					<< query.lastError().driverText() << ")";


		// Retrieve all available keys (values are retrieved lazily)
		if( query.exec( QLatin1String( "SELECT key FROM settings" ) ) ){
			while( query.next() ){
				d->m_settings.insert( query.value(0).toString(), QVariant() );
			}
		}
	}
}

SettingsSQL::~SettingsSQL(){
	//sync();

	delete d;

	QSqlDatabase::removeDatabase( "settings" );

}

void SettingsSQL::setValue(const QString &key, const QVariant &value){
	const QString effectiveKey = d->effectiveKey( key );

	// Add to cache
	d->m_settings.insert( effectiveKey, value );

	if( !d->m_db.isOpen() ){
		qWarning() << "SettingsSQL -> setValue -> db isn't open";
		return;
	}

	// Instant apply (TODO: Delay writing out settings)
	QSqlQuery query( d->m_db );
	query.prepare( "INSERT INTO settings VALUES (?, ?)" );
	query.addBindValue( effectiveKey );
	query.addBindValue( value );
	query.exec();

#ifdef DEBUG_SETTINGS
	qDebug() << "Stored:" << effectiveKey << "=" << value;
#endif
}

QVariant SettingsSQL::value(const QString &key,
							const QVariant &defaultValue) const
{
	const QString effectiveKey = d->effectiveKey( key );
	QVariant value = defaultValue;

	SettingsMap::const_iterator i = d->m_settings.constFind( effectiveKey );
	if( i != d->m_settings.constEnd() && i.value().isValid() ){
		value = i.value();
	}else{
		if (d->m_db.isOpen()) {
			// Try to read the value from the database
			QSqlQuery query( d->m_db );
			query.prepare( "SELECT value FROM settings WHERE key = ?" );
			query.addBindValue( effectiveKey );
			query.exec();

			if( query.next() ){
				value = query.value( 0 );

#ifdef DEBUG_SETTINGS
				qDebug() << "Retrieved:" << effectiveKey << "=" << value;
#endif
			}

			// Cache the result
			d->m_settings.insert( effectiveKey, value );
		}else{
			qWarning() << "SettingsSQL -> value -> db isn't open";
		}
	}

	return value;
}

bool SettingsSQL::contains(const QString &key) const {
	return d->m_settings.contains( d->effectiveKey( key ) );
}

void SettingsSQL::remove(const QString &key){
	const QString effectiveKey = d->effectiveKey( key );

	// Remove keys from the cache
	foreach( const QString &k, d->m_settings.keys() ){
		// Either it's an exact match, or it matches up to a /
		if( k.startsWith( effectiveKey )
			&& ( k.length() == effectiveKey.length()
				 || k.at( effectiveKey.length() ) == QLatin1Char( '/' ) ) )
			{
			d->m_settings.remove( k );
		}
	}

	if( !d->m_db.isOpen() ){
		qWarning() << "SettingsSQL -> remove -> db isn't open";
		return;
	}

	// Delete keys from the database
	QSqlQuery query( d->m_db );
	query.prepare( "DELETE FROM settings WHERE key = ? OR key LIKE ?" );
	query.addBindValue( effectiveKey );
	query.addBindValue( QString( effectiveKey + QLatin1String( "/%" ) ) );
	query.exec();
}

void SettingsSQL::beginGroup(const QString &prefix){
	d->m_groups.append( prefix );
}

void SettingsSQL::endGroup(){
	d->m_groups.removeLast();
}

QString SettingsSQL::group() const {
	return d->effectiveGroup();
}

QStringList SettingsSQL::childKeys() const {
	QStringList children;

	const QString g = group();
	QMapIterator<QString, QVariant> i( d->m_settings );
	while( i.hasNext() ){
		const QString &key = i.next().key();
		if (key.startsWith(g)
			&& key.indexOf(QLatin1Char('/'), g.length() + 1) == -1)
			{
			children.append( key.mid( g.length() + 1 ) );
		}
	}

	return children;
}

/*
void SettingsSQL::sync(){
	// TODO: Delay writing of dirty keys and save them here
}
*/

